package com.xmy.cultivate.characteristic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.Organization;
import com.xmy.cultivate.entity.Staff;
import com.xmy.cultivate.entity.TrackDetail;
import com.xmy.cultivate.entity.TrackMarket;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TrackCharacteristic {
    @Autowired
    ITrackService iTrackService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    ITrackDetailService iTrackDetailService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    ITrackMarketService iTrackMarketService;

    @Autowired
    IMqPushService iMqPushService;

    @ApiOperation("无限树处理")
    public List<TrackMarket> getCategory(List<TrackMarket> list, Long pid) {
        List<TrackMarket> result = new ArrayList<>();
        for (TrackMarket trackMarket : list) {
            if (Objects.equals(trackMarket.getPid(), pid)) {
                trackMarket.setChildren(getCategory(list, trackMarket.getId()));
                result.add(trackMarket);
            }
        }
        return result;
    }

    public IPage<TrackMarket> findAll(Map<String, String> reMap, int trackType) {
        int pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.parseInt(reMap.get("pageNum"));
        int pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.parseInt(reMap.get("pageSize"));
        IPage<TrackMarket> iPage = new Page<>(pageNum, pageSize);
        String name = reMap.get("name");
        String yearClassId = reMap.get("yearClassId");
        String classify = reMap.get("classify");//分类：1是续班赛道，2是招生赛道

        if (StringUtils.isEmpty(classify)) {
            classify = "1";
        }

        String yearPart = null;
        if (reMap.get("yearPart") != null && !reMap.get("yearPart").isEmpty()) {
            yearPart = reMap.get("yearPart");
        }
        String quarterNum = null;
        if (reMap.get("quarterNum") != null && !reMap.get("quarterNum").isEmpty()) {
            quarterNum = reMap.get("quarterNum");
        }

//        QueryWrapper<TrackMarket> queryWrapper = new QueryWrapper<>();
//        if (trackType == 1) {
//            queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
//        }
//        if (trackType == 2) {
//            queryWrapper.like(StringUtils.isNotBlank(name), "team_name", name);
//        }
//        queryWrapper.eq("classify", classify);
//        queryWrapper.eq("deleted", 0);
//        queryWrapper.eq("track_type", trackType);
//        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
//        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
//        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
//
//        iTrackMarketService.page(iPage, queryWrapper);

        // 获取大战队
        QueryWrapper<TrackMarket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classify", classify);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("pid", 0);
        queryWrapper.eq("track_type", trackType);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        iTrackMarketService.page(iPage, queryWrapper);

        if (iPage.getRecords().isEmpty()) {
            return iPage;
        }

        Set<Long> parentIds = iPage.getRecords().stream().map(TrackMarket::getId).collect(Collectors.toSet());
        List<TrackMarket> allChildren = new ArrayList<>();

        while (!parentIds.isEmpty()) {
            QueryWrapper<TrackMarket> childWrapper = new QueryWrapper<>();
            childWrapper.in("pid", parentIds);
            childWrapper.eq("deleted", 0);
            childWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
            if (trackType == 1) {
                childWrapper.like(StringUtils.isNotBlank(name), "name", name);
            }
            if (trackType == 2) {
                childWrapper.like(StringUtils.isNotBlank(name), "team_name", name);
            }
            List<TrackMarket> children = iTrackMarketService.list(childWrapper);
            allChildren.addAll(children);
            parentIds = children.stream().map(TrackMarket::getId).collect(Collectors.toSet());
        }

        List<TrackMarket> allChapters = new ArrayList<>();
        allChapters.addAll(iPage.getRecords());
        allChapters.addAll(allChildren);

        Map<Long, List<TrackMarket>> chapterMap = allChapters.stream().collect(Collectors.groupingBy(TrackMarket::getPid));

        buildTree(iPage.getRecords(), chapterMap);

        return iPage;
    }

    /**
     * 构建树结构
     *
     * @param chapters   父级
     * @param chapterMap 子集
     */
    private void buildTree(List<TrackMarket> chapters, Map<Long, List<TrackMarket>> chapterMap) {
        for (TrackMarket chapter : chapters) {
            List<TrackMarket> children = chapterMap.getOrDefault(chapter.getId(), new ArrayList<>());
            chapter.setChildren(children);
            buildTree(children, chapterMap);
        }
    }


    public Result findById(Long id) {
        TrackMarket trackMarket = iTrackMarketService.getById(id);
        return new Result(Code.OK, trackMarket);
    }

    public Result save(TrackMarket trackMarket, int trackType) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", trackMarket.getTeacherId());
        queryWrapper.eq("track_type", trackType);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("classify", trackMarket.getClassify());
        queryWrapper.eq("year_part", trackMarket.getYearPart());
        queryWrapper.eq("quarter_num", trackMarket.getQuarterNum());
        if (trackMarket.getYearClassId() != null) {
            queryWrapper.eq("year_class_id", trackMarket.getYearClassId());
        }
        if (trackMarket.getSchoolId() != null) {
            queryWrapper.eq("school_id", trackMarket.getSchoolId());
        }

        long count = iTrackMarketService.count(queryWrapper);
        if (count > 0) {
            return new Result(Code.ERROR, "", "请勿重复添加");
        }
        Staff staffServiceById = iStaffService.getById(trackMarket.getTeacherId());
        if (staffServiceById != null) {
            trackMarket.setName(staffServiceById.getName());
        }
        trackMarket.setTrackType(trackType);
        if (trackMarket.getPid() != null && trackMarket.getPid() > 0L) {
            TrackMarket trackMarketServiceById = iTrackMarketService.getById(trackMarket.getPid());
            if (trackMarketServiceById != null && trackMarketServiceById.getPid() != null && trackMarketServiceById.getPid() > 0L) {
                String treeLevel = trackMarketServiceById.getTreeLevel();
                trackMarket.setTreeLevel(treeLevel + "," + trackMarket.getPid());
            } else {
                trackMarket.setTreeLevel(trackMarket.getPid().toString());
            }
        }
        iTrackMarketService.save(trackMarket);
        iMqPushService.updateMarket(trackMarket);
        return new Result(Code.OK);
    }

    public Result update(TrackMarket trackMarket) {
        Staff staffServiceById = iStaffService.getById(trackMarket.getTeacherId());
        if (staffServiceById != null) {
            trackMarket.setName(staffServiceById.getName());
        }
        if (trackMarket.getPid() != null && trackMarket.getPid() > 0L) {
            TrackMarket trackMarketServiceById = iTrackMarketService.getById(trackMarket.getPid());
            if (trackMarketServiceById != null && trackMarketServiceById.getPid() != null && trackMarketServiceById.getPid() > 0L) {
                String treeLevel = trackMarketServiceById.getTreeLevel();
                trackMarket.setTreeLevel(treeLevel + "," + trackMarket.getPid());
            } else {
                trackMarket.setTreeLevel(trackMarket.getPid().toString());
            }
        } else {
            trackMarket.setTreeLevel("");
        }
        //处理换级后的树级数据
        List<TrackMarket> trackMarketList = iTrackMarketService.list(new QueryWrapper<TrackMarket>().apply("FIND_IN_SET('" + trackMarket.getId() + "',tree_level)"));
        if (!trackMarketList.isEmpty()) {
            String treeLevel = "";
            if (trackMarket.getPid() != null && trackMarket.getPid() > 0L) {
                treeLevel = trackMarket.getTreeLevel() + ",";
            }
            for (TrackMarket trackMarket1 : trackMarketList) {
                String[] strings = trackMarket1.getTreeLevel().split(trackMarket.getId().toString());
                String treeLevel1 = "";
                if (strings.length > 1) {
                    treeLevel1 = strings[1];
                }
                trackMarket1.setTreeLevel(treeLevel + trackMarket.getId() + treeLevel1);
                iTrackMarketService.updateById(trackMarket1);
            }
        }
        iTrackMarketService.updateById(trackMarket);
        iMqPushService.updateMarket(trackMarket);
        return new Result(Code.OK);
    }

    public Result delete(Long id) {
        TrackMarket trackMarket = iTrackMarketService.getById(id);
        boolean rs = iTrackMarketService.removeById(id);
        if (rs) {
            iTrackMarketService.remove(new QueryWrapper<TrackMarket>().apply("FIND_IN_SET('" + id + "',tree_level)"));
            iMqPushService.updateMarket(trackMarket);
        }
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    public Result addBatchSourse(TrackDetail trackDetail) {
        TrackDetail detail = iTrackMarketService.addBatchSourse(trackDetail);
        if (detail == null || Objects.isNull(detail) || detail.getTrackId() == null) {
            return new Result(Code.OK);
        }
        TrackMarket trackMarketServiceById = iTrackMarketService.getById(detail.getTrackId());
        String teanName = "";
        if (trackMarketServiceById != null) {
            teanName += "：" + trackMarketServiceById.getTeamName();
        }
        return new Result(Code.ERROR, "", "添加失败！已在“" + teanName + "”中添加！");
    }

    public Result deleteBatchSourse(TrackMarket trackMarket) {
        //先删除英语学习系统的数据
        for (Long id : trackMarket.getSourseIdList()) {
            TrackDetail trackDetail = iTrackDetailService.getById(id);
            if (trackDetail != null) {
                trackDetail.setDeleted(1);
                iMqPushService.updateTrackDetail(trackDetail);
            }
        }
        boolean rs = iTrackDetailService.removeBatchByIds(trackMarket.getSourseIdList());
        return new Result(rs ? Code.OK : Code.ERROR);
    }


    /**
     * @param isRepetition 是否允许重复
     */
    public Result checkTeacher(Map<String, String> reMap,
                               String[] schoolIdList,
                               String isRepetition) {
        int pageNum = reMap.get("pageNum") != null && !reMap.get("pageNum").isEmpty() ? Integer.parseInt(reMap.get("pageNum")) : 1;
        int pageSize = reMap.get("pageSize") != null && !reMap.get("pageSize").isEmpty() ? Integer.parseInt(reMap.get("pageSize")) : 1000;

        IPage<Staff> page = new Page<>(pageNum, pageSize);

        String status = "1";

        String trackId = reMap.get("trackId");

        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        staffQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);

        if (schoolIdList.length > 0) {
            String schoolIdStr = String.join(",", schoolIdList);
            staffQueryWrapper.in("school_id", schoolIdStr);

        }

        String name = reMap.get("name");
        if (StringUtils.isNotBlank(name)) {
            staffQueryWrapper.like("name", name);
        }

        if (StringUtils.isNotBlank(trackId)) {
            TrackMarket trackMarketInfo = iTrackMarketService.getById(trackId);
            if (trackMarketInfo == null) {
                return new Result(Code.ERROR, "", "赛道不存在");
            }
            if (StringUtils.isNotBlank(isRepetition) && isRepetition.equals("1")) {
                staffQueryWrapper.notInSql("id", "select sourse_id from track_detail where type = " + trackMarketInfo.getType() + " and deleted=0 and classify=" + trackMarketInfo.getClassify() + " and track_id=" + trackMarketInfo.getId());
            } else {
                staffQueryWrapper.notInSql("id", "select sourse_id from track_detail where type = " + trackMarketInfo.getType() + " and deleted=0 and classify=" + trackMarketInfo.getClassify());
            }
        }

        iStaffService.findAll(page, staffQueryWrapper);

        return new Result(Code.OK, new PageResult<>(page.getRecords(), page.getTotal(), page.getPages()));
    }

    public Result checkSchool(Map<String, Object> reMap) {
        int pageNum = reMap.get("pageNum") != null && !reMap.get("pageNum").toString().isEmpty() ? Integer.parseInt(reMap.get("pageNum").toString()) : 1;
        int pageSize = reMap.get("pageSize") != null && !reMap.get("pageSize").toString().isEmpty() ? Integer.parseInt(reMap.get("pageSize").toString()) : 1000;

        IPage<Organization> page = new Page<>(pageNum, pageSize);

        String trackId = (String) reMap.get("trackId");

        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();

        String name = (String) reMap.get("name");
        if (StringUtils.isNotBlank(name)) {
            organizationQueryWrapper.like("name", name);
        }

        if (StringUtils.isNotBlank(trackId)) {
            organizationQueryWrapper.notInSql("id", "select sourse_id from track_detail where type = 2 and deleted=0 and track_id=" + trackId);
        }

        organizationQueryWrapper.eq("type", 1);

        iOrganizationService.page(page, organizationQueryWrapper);

        return new Result(Code.OK, new PageResult<>(page.getRecords(), page.getTotal(), page.getPages()));
    }

}
